package com.hj.system.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hj.system.utils.ResponseUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Stream;

/**
 * 基础controller
 * T 实体类
 * M service
 */
public abstract class BaseController<T extends Serializable, M extends IService<T>> {

    public abstract M getBaseService();

    public IPage page(int page, int limit, T t) {
        Wrapper<T> queryWrapper = new QueryWrapper<>(t);
        Page<T> pageEntity = new Page<>(page, limit);
        IPage<T> iPage = getBaseService().page(pageEntity, queryWrapper);
        return iPage;
    }

    @GetMapping("/page")
    public ResponseUtil queryPage(int page, int limit, T t) {
        IPage<T> iPage = page(page, limit, t);
        return ResponseUtil.okContent(iPage);
    }

    @GetMapping("/{id}")
    public ResponseUtil findById(@PathVariable("id") String id) {
        T t = getBaseService().getById(id);
        return ResponseUtil.okContent(t);
    }

    @GetMapping("/list")
    public ResponseUtil findList(T queryT) {
        List<T> t = getBaseService().list(new QueryWrapper<>(queryT));
        return ResponseUtil.okContent(t);
    }

    @PostMapping("/update")
    public ResponseUtil update(T t) {
        boolean flag = getBaseService().updateById(t);
        if (flag) {
            return ResponseUtil.ok("更新成功");
        }
        return ResponseUtil.error("更新出错");
    }

    @PostMapping("/add")
    public ResponseUtil add(T t) {
        boolean flag = getBaseService().save(t);
        if (flag) {
            return ResponseUtil.okContent(t);
        }
        return ResponseUtil.error("保存出错");
    }

    @PostMapping("/delete/{id}")
    public ResponseUtil deleteById(@PathVariable("id") String id) {
        boolean flag = getBaseService().removeById(id);
        if (flag) {
            return ResponseUtil.ok("删除成功");
        }
        return ResponseUtil.error("删除出错");
    }


}
